package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 修改用户密码界面
 */
public class MyProfilePasswordActivity extends RootActivity {

    private static final String TAG = "MyProfilePassword";

    private ImageView iv_my_profile_password_back;
    private TextView tv_my_profile_password_save;

    private EditText et_my_profile_original_password_content;
    private ImageView iv_original_password_judge;

    private EditText et_my_profile_new_password_content;
    private ImageView iv_new_password_judge;

    private EditText et_my_profile_confirm_password_content;
    private ImageView iv_confirm_password_judge;

    private EditText et_my_profile_password_email_address;
    private EditText et_my_profile_password_captcha;
    private Button btn_my_profile_password_send_code;

    private Bundle bundle;

    private String uid;
    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;

    private boolean originalJudge = false;
    private boolean newJudge = false;
    private boolean confirmNewJudge = false;

    private String newPassword;
    private String originalPassword;
    private String email_address;

    private boolean threadRun;
    private Message timeMsg;
    /**
     * 主线程修改UI
     */
    private Handler handlerChangeBt = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (threadRun) {
                        if ("0s".equals(msg.obj)) {
                            stopTimeKeepingThread();
                            return;
                        }
                        btn_my_profile_password_send_code.setText(msg.obj + "");
                    }
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile_password);

        bundle = this.getIntent().getExtras();
        uid = bundle.getString("uid");

        initView();
        initViewListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        iv_my_profile_password_back = (ImageView) findViewById(R.id.iv_my_profile_password_back);

        et_my_profile_original_password_content = (EditText) findViewById(R.id.et_my_profile_original_password_content);
        iv_original_password_judge = (ImageView) findViewById(R.id.iv_original_password_judge);

        et_my_profile_new_password_content = (EditText) findViewById(R.id.et_my_profile_new_password_content);
        iv_new_password_judge = (ImageView) findViewById(R.id.iv_new_password_judge);

        et_my_profile_confirm_password_content = (EditText) findViewById(R.id.et_my_profile_confirm_password_content);
        iv_confirm_password_judge = (ImageView) findViewById(R.id.iv_confirm_password_judge);

        tv_my_profile_password_save = (TextView) findViewById(R.id.tv_my_profile_password_save);

        et_my_profile_password_email_address = (EditText) findViewById(R.id.et_my_profile_password_email_address);
        et_my_profile_password_captcha = (EditText) findViewById(R.id.et_my_profile_password_captcha);
        btn_my_profile_password_send_code = (Button) findViewById(R.id.btn_my_profile_password_send_code);
        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);
    }

    /**
     * 初始化组件监听
     */
    private void initViewListener() {
        //回退按钮事件监听
        iv_my_profile_password_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //保存用户密码点击事件监听
        tv_my_profile_password_save.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Editable code = et_my_profile_password_captcha.getText();
                if(null == code || "".equals(code)){
                    Toast.makeText(MyProfilePasswordActivity.this.getApplicationContext(), ToastConstant.INPUT_CAPTCHA_FIRST, Toast.LENGTH_SHORT).show();
                    return;
                }

                //向后台修改密码
                if(originalJudge && newJudge && confirmNewJudge){
                    Map<String, String> params = new HashMap<>();
                    params.put(WebConstant.RESET_PASSWORD_PATH_EMAIL, email_address);
                    params.put(WebConstant.RESET_PASSWORD_PATH_PASSWORD, newPassword);
                    params.put(WebConstant.RESET_PASSWORD_PATH_CODE, code.toString());
                    new GetJsonFromWebJob(WebConstant.RESET_PASSWORD_PATH, WebConstant.PUT, params, REQUEST_SIGN_CHANGE_PASSWORD, MyProfilePasswordActivity.this).start();
                }
            }
        });

        //确认原始密码
        et_my_profile_original_password_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                iv_original_password_judge.setVisibility(View.VISIBLE);
                //与sp中存储的密码进行比较
                if (null == s) {
                    Log.e(TAG, "afterTextChanged: -------------------- 输入的原始密码为空");
                    return;
                }
                //和sp中原密码 比较 成功
                if (s.toString().equals(handleDataBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, SpConstant.USER_INFO_PASSWORD_KEY))){
                    iv_original_password_judge.setImageResource(R.drawable.ic_confirm_password_true);
                    originalPassword = s.toString();
                    originalJudge = true;
                    return;
                }
                //比较 失败
                iv_original_password_judge.setImageResource(R.drawable.ic_confirm_password_false);
                originalJudge = false;
            }
        });

        //输入新密码
        et_my_profile_new_password_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                //与sp中存储的密码进行比较
                if (null == s) {
                    Log.e(TAG, "afterTextChanged: -------------------- 输入的原始密码为空");
                    return;
                }

                if(originalPassword.equals(s.toString())){
                    Toast.makeText(MyProfilePasswordActivity.this.getApplicationContext(), ToastConstant.NEW_PASSWORD_NOT_CHANGE, Toast.LENGTH_SHORT).show();
                    return;
                }
                iv_new_password_judge.setVisibility(View.VISIBLE);
                newPassword = s.toString();
                iv_new_password_judge.setImageResource(R.drawable.ic_confirm_password_true);
                newJudge = true;
            }
        });

        //确认新密码
        et_my_profile_confirm_password_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                iv_confirm_password_judge.setVisibility(View.VISIBLE);
                //与sp中存储的密码进行比较
                if (null == s) {
                    Log.e(TAG, "afterTextChanged: -------------------- 输入的原始密码为空");
                    return;
                }
                //和sp中原密码 比较 一致1
                if (newPassword.equals(s.toString())){
                    iv_confirm_password_judge.setImageResource(R.drawable.ic_confirm_password_true);
                    confirmNewJudge = true;
                    return;
                }
                //比较 不一致
                iv_confirm_password_judge.setImageResource(R.drawable.ic_confirm_password_false);
                confirmNewJudge = false;
            }
        });

        //获取验证码
        btn_my_profile_password_send_code.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否输入邮箱地址
                if (null == et_my_profile_password_email_address.getText() || "".equals(et_my_profile_password_email_address.getText().toString())) {
                    Toast.makeText(MyProfilePasswordActivity.this.getApplicationContext(), ToastConstant.INPUT_EMAIL_ADDRESS_FIRST, Toast.LENGTH_SHORT).show();
                    return;
                }
                email_address = et_my_profile_password_email_address.getText().toString();
                //请求验证码按钮不可按
                btn_my_profile_password_send_code.setEnabled(false);

                //向服务器请求邮箱验证码
                Map<String, String> params_response_code = new HashMap<>();
                params_response_code.put(WebConstant.GET_EMAIL_AUTH_PATH_CHECK, "2");
                new GetJsonFromWebJob(WebConstant.GET_EMAIL_AUTH_PATH + email_address, WebConstant.POST, params_response_code, REQUEST_SIGN_GET_EMAIL_CAPTCHA, MyProfilePasswordActivity.this).start();

                //开启计时线程，修改验证码发送的时机
                threadRun = true;
                new TimeKeepingThread().start();
            }
        });

        //输入邮箱 内容监听
        et_my_profile_password_email_address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!"Send code".equals(btn_my_profile_password_send_code)) {
                    btn_my_profile_password_send_code.setText("Send code");
                    threadRun = false;
                }
                btn_my_profile_password_send_code.setEnabled(true);
            }
        });
    }

    /**
     * 处理从网络获取的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        //判断获取验证码 手机号已存在
        if (webResult.contains("user already existed")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.PHONE_HAS_BEEN_USED, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 手机号已存在");
            stopTimeKeepingThread();
            return;
        }

        //判断缺少参数
        if (webResult.contains("MissingParameter")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.NETWORK_FAILURE, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 缺少参数");
            stopTimeKeepingThread();
            return;
        }
        //判断邮箱未注册
        if (webResult.contains("none user or incorrect password")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.NONE_USER_OR_PASSWORD_WRONG, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 用户不存在或密码错误");
            stopTimeKeepingThread();
            return;
        }
        //判断验证码已过期
        if (webResult.contains("verification code expired")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_EXPIRE, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 验证码已过期");
            stopTimeKeepingThread();
            return;
        }
        //判断验证码不匹配
        if (webResult.contains("verification code mismatched")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_MISMATCH, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 验证码不匹配");
            stopTimeKeepingThread();
            return;
        }

        //判断缺少参数
        if (webResult.contains("none parameter")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.NETWORK_FAILURE, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: ----------------- 缺少参数");
            return;
        }
        //判断用户不存在
        if (webResult.contains("none user")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.ACCOUNT_NOT_EXIST, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: ------------- 用户不存在");
            return;
        }

        //修改密码成功，跳转到登录界面
        if (REQUEST_SIGN_CHANGE_PASSWORD == webSign && "".equals(webResult)) {
            //将数据存储到SharePreferences中
            Map<String, String> params_register_info = new HashMap<>();
            params_register_info.put("password", newPassword);
            handleDataBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME, params_register_info);

            activityChange(LOGIN_ACTIVITY, null, null);
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            }catch (Exception e){
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }

    /**
     * 验证码重发计时线程
     */
    class TimeKeepingThread extends Thread {
        @Override
        public void run() {
            for (int i = 60; i >= 0; i--) {
                if (threadRun) {
                    SystemClock.sleep(990);
                    timeMsg.obj = i + "s";
                    handlerChangeBt.handleMessage(timeMsg);
                }
            }
        }

    }

    private void stopTimeKeepingThread() {
        threadRun = false;
        btn_my_profile_password_send_code.setEnabled(true);
        btn_my_profile_password_send_code.setText("Send code");
    }
}
